<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Index extends Controller_Template 
{
    public $template = 'v_index';
	
    public function before()
    {
	    parent::before();
        $this->template->styles = array(
		    'styles/style.css',
		    'styles/jquery.lightbox-0.5.css'
		);

        $this->template->scripts = array(
		    'js/jquery-2.1.0.min.js', 
		    'js/ajax.show.images.js',
		    'js/jquery.lightbox-0.5.pack.js'
        );
    }

    public function action_index()
    {
	    $db_rows = NULL;
	    $filename = NULL;
	    $content = View::factory('v_index');
	    $images = ORM::factory('Mgallery')->get_all_images();
	    $table_images_rows = count($images);
        $this->template->images = $images;
        $this->template->table_images_rows = $table_images_rows;

        if ($this->request->method() == Request::POST)
        {
		    if (isset($_FILES['image_selector']))
		    {
			    $filename = $this->
				    _save_image($_FILES['image_selector'], 
				    $this->request->post('image_description'));
            }
        }
    }

    protected function _save_image($image, $image_description)
    {
	    if(!Upload::valid($image) || !Upload::not_empty($image) || 
		    !Upload::type($image, array('jpg', 'jpeg', 'png', 'gif')))
        {
            echo "<h1 style='color: red;'>Error</h1>";
            return FALSE;
        }

        $directory = DOCROOT.'uploads/';
        
        if ($file = Upload::save($image, NULL, $directory))
        {
            $filename = strtolower($image['name']);
            $name_image = $filename;

            Image::factory($file)
                ->resize(600, 450, Image::AUTO)
                ->save($directory.$filename);

            Image::factory($file)
                ->resize(200, 150, Image::NONE)
                ->save($directory."200x150_".$filename);

            unlink($file);
            $insert = ORM::factory('Mgallery')->
                insert_image($name_image, $image_description);
           	
            $this->request->redirect($_SERVER['HTTP_REFERER']);
        }
        return FALSE;
    }
}